import axios from "axios";
import { useUserStore } from "@/store/module/user";
import router from "@/router";
import { message } from "ant-design-vue";

//封装axios,请求基地址，超时时间，请求拦截器，响应拦截器
const request = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.Authorization = "Bearer " + userStore.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    // console.log(response);
    // if (response.data.code === 200) {
      
    // }
    return response.data;
  },
  (error) => {
    // console.log(error);
    const userStore = useUserStore();
    if (error.response.data.code === 401) {
      userStore.clearUserInfo()
      router.push("/login");
      message.error(error.response.data.msg);
    }
    return Promise.reject(error);
  }
);

export default request;
